package com.ittao.taoaicodecommon.manage.storage.callback.impl;

import com.ittao.taoaicodecommon.manage.storage.callback.DownloadProgressCallback;
import com.ittao.taoaicodecommon.manage.storage.entity.DownloadStatistics;
import com.ittao.taoaicodecommon.manage.storage.entity.PerformanceMetrics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 性能监控下载进度回调实现类
 * 用于监控文件下载进度和性能指标
 */
@Slf4j
@Component
public class PerformanceMonitoringCallbackImpl implements DownloadProgressCallback {

    private final AtomicLong totalBytesTransferred = new AtomicLong(0);
    private final AtomicLong completedFiles = new AtomicLong(0);
    private final AtomicLong failedFiles = new AtomicLong(0);

    private DownloadStatistics statistics;
    private PerformanceMetrics performanceMetrics;
    private long lastProgressTime = System.currentTimeMillis();

    /**
     * 初始化回调
     * @param statistics 下载统计信息
     * @param performanceMetrics 性能指标
     */
    public void initialize(DownloadStatistics statistics, PerformanceMetrics performanceMetrics) {
        this.statistics = statistics;
        this.performanceMetrics = performanceMetrics;
        this.totalBytesTransferred.set(0);
        this.completedFiles.set(0);
        this.failedFiles.set(0);
        this.lastProgressTime = System.currentTimeMillis();
    }

    @Override
    public void onStart(int totalFiles, long totalSize) {
        log.debug("开始下载任务: 总文件数={}, 总大小={} bytes", totalFiles, totalSize);
    }

    @Override
    public void onProgress(int completedFiles, long downloadedSize, int totalFiles, long totalSize) {
        totalBytesTransferred.set(downloadedSize);

        // DownloadStatistics使用AtomicLong，通过getDownloadedSize()获取原子操作对象
        if (statistics != null) {
            statistics.getDownloadedSize().set(downloadedSize);
        }

        // 每5秒记录一次进度日志
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastProgressTime > 5000) {
            double progress = totalSize > 0 ? (double) downloadedSize / totalSize * 100 : 0;
            log.info("下载进度: {}%, 已下载: {} bytes, 总大小: {} bytes",
                    progress, downloadedSize, totalSize);
            lastProgressTime = currentTime;
        }
    }

    @Override
    public void onFileCompleted(String fileName, long fileSize) {
        completedFiles.incrementAndGet();
        log.debug("文件下载完成: {}, 大小: {} bytes", fileName, fileSize);
    }

    @Override
    public void onFileError(String fileName, Exception error) {
        failedFiles.incrementAndGet();

        // 记录错误到性能指标
        if (performanceMetrics != null) {
            performanceMetrics.recordError("文件下载失败: " + fileName + ", 错误: " + error.getMessage());
        }

        log.error("文件下载失败: {}, 错误: {}", fileName, error.getMessage());
    }

    @Override
    public void onComplete(int completedFiles, long downloadedSize, long duration) {
        // 完成操作记录
        if (performanceMetrics != null) {
            performanceMetrics.complete();
        }

        log.info("下载任务完成 - 成功: {}, 失败: {}, 总传输: {} bytes, 耗时: {} ms",
                completedFiles, failedFiles.get(), downloadedSize, duration);
    }

    @Override
    public void onError(Exception error) {
        // 记录全局错误
        if (performanceMetrics != null) {
            performanceMetrics.recordError("下载任务全局错误: " + error.getMessage());
        }

        log.error("下载任务发生错误: {}", error.getMessage());
    }

}